#include <iostream>
#include <errno.h>

using namespace std;

#include "socket.h"

Socket::Socket(int family, int protocol){

  m_sockfd = socket(family, protocol, 0);//makes a socket

  m_family = family;

  m_type = protocol;
    
  int optval = 1;

  peer_addr_length = sizeof(m_peer_addr);

  if(m_sockfd == -1){
    
    cout << strerror(errno) << endl;

  }
  else{

    cout<< "Socket Made" << endl;

  }

    
  if(setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1 ||
     setsockopt(m_sockfd, SOL_SOCKET, SO_NOSIGPIPE, &optval, sizeof(optval)) == -1) 
    {
        
        cout << "Error Setting Option" << endl;
        
    }


}

Socket::Socket(){}

int Socket::Bind(int port){

  int m_port = port;

  //Creates the address struct for this socket
  memset(&m_host_addr, 0, sizeof(struct sockaddr_in));

  m_host_addr.sin_family = m_family;
  m_host_addr.sin_port = htons(m_port);
  m_host_addr.sin_addr.s_addr = htonl(INADDR_ANY);


  //binds the socket to m_port
  int err = bind(m_sockfd, (sockaddr*)&m_host_addr, sizeof(struct sockaddr));

  if(err == -1){

    cout << strerror(errno) << endl;

  }
  else{

    cout<< "Socket Bound" << endl;

  }

  return err;

}

int Socket::Listen(){return -1;}

Socket* Socket::Accept(){return NULL;}

int Socket::Connect(char* address, int port){return -1;}

void Socket::SetPeerAddress(char* address, int port){}

int Socket::Close(){

  int err = close(m_sockfd);

  if(err == 0){
    
    cout << "Socket Closed" << endl;

  }
  else if(err == -1){

    cout << strerror(errno) << endl;

  }

  return err;

}

string Socket::GetPeerAddress(){

  char address[100];
  int length = 100;

  inet_ntop(AF_INET, (void*)&m_peer_addr.sin_addr, address, length);

  string addr(address);

  return addr;

}

void Socket::SetPeerAddress(sockaddr_in addr){

  memcpy(&m_peer_addr, &addr, sizeof(addr));

}
